package com.soufang.ui;

import java.util.Iterator;

import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class gpsFragment extends Fragment {
	
	private EditText text1; 
	private TextView tv_gps; 
	private  LocationManager lm;  
	private static final String TAG="GPS Services";  
	
	@Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.gps_layout, container, false);
		text1=(EditText)v.findViewById(R.id.text1);  
        tv_gps=(TextView)v.findViewById(R.id.tv_gps);
        boolean bgetGps = registerGPS();  
        //为获取地理位置信息时设置查询条件   
        String bestProvider = lm.getBestProvider(getCriteria(), true);  
        System.out.println("这是bestProvider："+bestProvider);
        //获取位置信息        //如果不设置查询要求，getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER      
        Location location= lm.getLastKnownLocation(bestProvider);   
        System.out.println("location:"+location);
        updateView(location);     
        lm.addGpsStatusListener(listener);      
        lm.requestLocationUpdates(bestProvider, 1000, 1, locationListener);
		return v;
	}  
	
	 private boolean registerGPS(){  
	        lm=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);  
	          
	        //判断GPS是否正常启动  
	        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
	            Toast.makeText(getActivity(), "请开启GPS导航...", Toast.LENGTH_SHORT).show();  
	            //返回开启GPS导航设置界面  
	            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);     
	            startActivityForResult(intent,0);   
	            return false;  
	        }  
	        return true;
	    }
	    
	    /**     * 实时更新文本内容     *      * @param location     */  
     private void updateView(Location location){  
             
             if(location!=null){         
             	text1.setText("获取经纬度：\n\n经度：");  
             	text1.append(String.valueOf(location.getLongitude())); 
             	text1.append("\n纬度：");       
             	text1.append(String.valueOf(location.getLatitude()));  
             }else{         
                     //清空EditText对象        
             	text1.getEditableText().clear(); 
             }  
     }    
      //位置监听  
     private LocationListener locationListener=new LocationListener() {  
             /**         * 位置信息变化时触发         */    
             public void onLocationChanged(Location location) {    
                     updateView(location);        
                     Log.i(TAG, "时间："+location.getTime());    
                     Log.i(TAG, "经度："+location.getLongitude());     
                     Log.i(TAG, "纬度："+location.getLatitude());      
                     Log.i(TAG, "海拔："+location.getAltitude());    
                     }             
             /**         * GPS状态变化时触发         */  
             public void onStatusChanged(String provider, int status, Bundle extras) {     
                     switch (status) {      
                     //GPS状态为可见时            
                     case LocationProvider.AVAILABLE:     
                             Log.i(TAG, "当前GPS状态为可见状态"); 
                             break;           
                             //GPS状态为服务区外时       
                             case LocationProvider.OUT_OF_SERVICE:      
                                     Log.i(TAG, "当前GPS状态为服务区外状态");   
                                     break;          
                                     //GPS状态为暂停服务时     
                                     case LocationProvider.TEMPORARILY_UNAVAILABLE:    
                                             Log.i(TAG, "当前GPS状态为暂停服务状态");     
                                             break;         
                                             }     
                     }           
             /**         * GPS开启时触发         */   
             public void onProviderEnabled(String provider) {     
                     Location location=lm.getLastKnownLocation(provider);  
                     updateView(location);        }        
             /**         * GPS禁用时触发         */     
             public void onProviderDisabled(String provider) {
                     updateView(null);       
                     }     
             };
     /**     * 返回查询条件     * @return     */  
     private Criteria getCriteria(){     
             Criteria criteria=new Criteria();   
             //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细       
             criteria.setAccuracy(Criteria.ACCURACY_FINE);         
             //设置是否要求速度       
             criteria.setSpeedRequired(false);    
             // 设置是否允许运营商收费          
             criteria.setCostAllowed(false);      
             //设置是否需要方位信息        
             criteria.setBearingRequired(false);  
             //设置是否需要海拔信息    
             criteria.setAltitudeRequired(false);      
             // 设置对电源的需求         
             criteria.setPowerRequirement(Criteria.POWER_LOW);    
             return criteria;   
     }
     
     
       //状态监听    
     GpsStatus.Listener listener = new GpsStatus.Listener() { 
             public void onGpsStatusChanged(int event) {    
                     switch (event) {        
                     //第一次定位       
                     case GpsStatus.GPS_EVENT_FIRST_FIX: 
                             Log.i(TAG, "第一次定位");       
                             break;           
                             //卫星状态改变          
                             case GpsStatus.GPS_EVENT_SATELLITE_STATUS:      
                                     Log.i(TAG, "卫星状态改变");          
                                     //获取当前状态           
                                     GpsStatus gpsStatus=lm.getGpsStatus(null);    
                                     //获取卫星颗数的默认最大值       
                                     int maxSatellites = gpsStatus.getMaxSatellites();       
                                     //创建一个迭代器保存所有卫星       
                                     Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();     
                                     int count = 0;                
                                     while (iters.hasNext() && count <= maxSatellites) {         
                                             GpsSatellite s = iters.next();                    
                                             count++;                     }  
                                     Log.i(TAG, "搜索到："+count+"颗卫星");    
                                     
                                     break;            //定位启动     
                                     case GpsStatus.GPS_EVENT_STARTED:   
                                             Log.i(TAG, "定位启动");           
                                             break;           
                                             //定位结束        
                                             case GpsStatus.GPS_EVENT_STOPPED:   
                                                     Log.i(TAG, "定位结束");         
                                                     break;      
                                                     }       
                     };  
     };
}
